<template>
  <div class="role-management">
    <el-button type="primary" size="small" style="margin-bottom:30px" @click="handleAdd">新增角色</el-button>

    <!-- 表格 -->
    <template>
      <el-table
        :data="roleList"
        stripe
        border
        align="center"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="100"
          label="序号"
          align="center"
        />
        <el-table-column
          align="center"
          prop="name"
          label="姓名"
          width="180"
        />
        <el-table-column
          align="center"
          prop="description"
          label="描述"
        />
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="success"
              @click="handlePermission(scope.row)"
            >分配权限</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 分页 -->
    <el-pagination
      layout="sizes, prev, pager, next"
      :total="total"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      :current-page.sync="page"
      @size-change="handleSizeChange"
      @current-change="getRoleListInfo"
    />

    <!-- 新增弹框 -->
    <el-dialog
      :title="type"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeDialog"
    >
      <el-form ref="role" :model="role" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="role.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="role.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限弹出框 -->

    <el-dialog
      v-if="permissionBox"
      title="提示"
      :visible.sync="permissionBox"
      width="30%"
    >
      <el-tree
        ref="tree"
        check-strictly
        :data="permissionList"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="permIds"
        :props="defaultProps"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="permissionBox = false">取 消</el-button>
        <el-button type="primary" @click="permissionComfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, delRoleInfo, addRoleInfo, editRoleInfo, getRoleInfo } from '@/api/setting'
import { getPermissionList, assignPermission } from '@/api/permission'
import { tranListToTreeData } from '@/utils/index'

export default {

  data() {
    return {
      roleList: [], // 角色列表
      permissionList: [], // 权限列表
      dialogVisible: false, // 新增弹框
      permissionBox: false, // 权限弹出框
      pageSize: 10,
      page: 1,
      type: '', // 新增或编辑
      total: 0,
      role: {
        name: '',
        description: '',
        id: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      defaultProps: {
        children: 'children',
        // 将展示文本的字段改成name，因为我们的后台给的是name字段
        label: 'name'
      },
      permIds: []

    }
  },
  created() {
    this.getRoleListInfo()
  },

  methods: {

    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.getRoleListInfo()
    },
    // 获取角色列表
    async getRoleListInfo(val) {
      this.page = val
      const { data } = await getRoleList(this.page, this.pageSize)
      this.total = data.total
      this.roleList = data.rows
    },
    // 处理新增角色button按钮
    handleAdd() {
      this.dialogVisible = true
      this.type = '新增角色'
    },
    // 处理编辑角色button按钮
    handleEdit(index, row) {
      this.dialogVisible = true
      this.type = '编辑角色'
      this.role.name = row.name
      this.role.description = row.description
      this.role.id = row.id
    },
    // 处理确定按钮
    handleConfirm() {
      this.$refs.role.validate(async valid => {
        if (valid) {
          if (this.type === '新增角色') {
            const res = await addRoleInfo(this.role)
            if (res.success) {
              this.$message({
                message: res.message,
                type: 'success'
              })
              this.dialogVisible = false
              this.getRoleListInfo()
            } else {
              this.$message.error('添加失败！')
            }
          } else {
            const res = await editRoleInfo(this.role.id, this.role)
            if (res.success) {
              this.$message({
                message: res.message,
                type: 'success'
              })
              this.dialogVisible = false
              this.getRoleListInfo()
            } else {
              this.$message.error('编辑失败！')
            }
          }
        }
      })
    },

    // 处理删除角色button按钮
    async handleDelete(index, row) {
      console.log(index, row)
      await this.delRole(row.id)
    },
    // 删除角色
    delRole(id) {
      this.$confirm('确定删除此角色？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delRoleInfo(id)
        if (res.code === 10000) {
          this.$message({
            type: 'success',
            message: res.message
          })
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
        this.getRoleListInfo()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 清空表单
    clearForm() {
      this.role.name = ''
      this.role.description = ''
    },
    // 关闭弹窗时清空表单
    closeDialog() {
      this.clearForm()
      // 将表单验证重置
      this.$refs.role.clearValidate()
    },
    // 处理权限button按钮
    async handlePermission(row) {
      const { data } = await getPermissionList()
      this.permissionList = tranListToTreeData(data, '0')
      this.role.id = row.id
      const res = await getRoleInfo(row.id)
      this.permIds = res.data.permIds
      this.permissionBox = true
      // this.$nextTick(() => {
      //   this.$refs.tree.setCheckedKeys(this.permIds)
      // })
    },
    // handleCheck(data, checked) {
    //   console.log(data, checked)
    //   if (checked) {
    //     this.permIds.push(data.id)
    //   } else {
    //     const index = this.permIds.indexOf(data.id)
    //     this.permIds.splice(index, 1)
    //   }
    //   console.log(this.permIds)
    // },
    async  permissionComfirm() {
      this.permIds = [...this.$refs.tree.getHalfCheckedKeys(), ...this.$refs.tree.getCheckedKeys()]
      const obj = { id: this.role.id, permIds: this.permIds }
      const res = await assignPermission(obj)
      if (res.success) {
        this.$message({
          message: res.message,
          type: 'success'
        })
        this.permissionBox = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-pagination{
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
::v-deep .el-dialog__footer{
  text-align: center;
}
// ::v-deep .el-input__inner{
//   width: 500px;
// }
</style>
